import React, { useState, useEffect } from 'react';
import './Notification.css';

export interface NotificationProps {
  message: string;
  type?: 'success' | 'error' | 'warning' | 'info';
  duration?: number;
  onClose?: () => void;
}

interface NotificationItem extends NotificationProps {
  id: string;
}

let notificationId = 0;

// 全局通知管理器
class NotificationManager {
  private notifications: NotificationItem[] = [];
  private listeners: ((notifications: NotificationItem[]) => void)[] = [];

  add(notification: Omit<NotificationProps, 'id'>) {
    const id = `notification-${++notificationId}`;
    const newNotification: NotificationItem = {
      ...notification,
      id,
    };

    this.notifications.push(newNotification);
    this.notifyListeners();

    // 自动关闭
    if (notification.duration !== 0) {
      setTimeout(() => {
        this.remove(id);
      }, notification.duration || 3000);
    }

    return id;
  }

  remove(id: string) {
    this.notifications = this.notifications.filter(n => n.id !== id);
    this.notifyListeners();
  }

  subscribe(listener: (notifications: NotificationItem[]) => void) {
    this.listeners.push(listener);
    return () => {
      this.listeners = this.listeners.filter(l => l !== listener);
    };
  }

  private notifyListeners() {
    this.listeners.forEach(listener => listener([...this.notifications]));
  }
}

export const notificationManager = new NotificationManager();

// 通知容器组件
export const NotificationContainer: React.FC = () => {
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);

  useEffect(() => {
    const unsubscribe = notificationManager.subscribe(setNotifications);
    return unsubscribe;
  }, []);

  return (
    <div className="notification-container">
      {notifications.map(notification => (
        <NotificationItem
          key={notification.id}
          {...notification}
          onClose={() => notificationManager.remove(notification.id)}
        />
      ))}
    </div>
  );
};

// 单个通知项组件
const NotificationItem: React.FC<NotificationItem> = ({
  message,
  type = 'info',
  onClose,
}) => {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    // 延迟显示动画
    const timer = setTimeout(() => setIsVisible(true), 10);
    return () => clearTimeout(timer);
  }, []);

  const handleClose = () => {
    setIsVisible(false);
    setTimeout(() => onClose?.(), 300); // 等待动画完成
  };

  return (
    <div
      className={`notification-item ${type} ${isVisible ? 'visible' : ''}`}
      onClick={handleClose}
    >
      <div className="notification-content">
        <div className="notification-icon">
          {type === 'success' && '✓'}
          {type === 'error' && '✕'}
          {type === 'warning' && '⚠'}
          {type === 'info' && 'ℹ'}
        </div>
        <div className="notification-message">{message}</div>
        <button className="notification-close" onClick={handleClose}>
          ×
        </button>
      </div>
    </div>
  );
};

// 便捷方法
export const notification = {
  success: (message: string, duration?: number) =>
    notificationManager.add({ message, type: 'success', duration }),
  error: (message: string, duration?: number) =>
    notificationManager.add({ message, type: 'error', duration }),
  warning: (message: string, duration?: number) =>
    notificationManager.add({ message, type: 'warning', duration }),
  info: (message: string, duration?: number) =>
    notificationManager.add({ message, type: 'info', duration }),
};
